import { Injectable } from '@nestjs/common'
import { CreateArticleDto } from './dto/create-article.dto'
import { UpdateArticleDto } from './dto/update-article.dto'
import { PrismaService } from '../prisma/prisma.service'
import { Prisma } from '@prisma/client'

@Injectable()
export class ArticleService {
    constructor(private readonly prisma: PrismaService) {}

    create(createArticleDto: CreateArticleDto) {
        return this.prisma.article.create({
            data: createArticleDto
        })
    }

    async findAll(query: { title: string, status?: number, categoryId?: number, pageIndex: number, pageSize: number }) {
        const total = await this.prisma.article.count({
            where: {
                title: { contains: query.title },
                status: query.status,
                categoryId: query.categoryId
            }
        })

        const list = await this.prisma.$queryRaw`
            SELECT
            *,
            (SELECT CAST(COUNT(1) AS REAL) FROM comment WHERE comment.articleId=article.id) AS commentCount,
            (SELECT [name] FROM category WHERE category.id=article.categoryId) AS categoryName 
            FROM article WHERE 1=1
            ${
                query.categoryId ? 
                Prisma.sql`AND categoryId=${query.categoryId}` : 
                Prisma.empty
            }
            ${
                typeof query.status === 'number' ? 
                Prisma.sql`AND status=${query.status}` : 
                Prisma.empty
            }
            ${
                query.title ? 
                Prisma.raw(`AND title LIKE '%${query.title}%'`) : 
                Prisma.empty
            }
            ORDER BY createTime DESC 
            LIMIT ${ Prisma.raw(`${query.pageSize} OFFSET ${(query.pageIndex - 1) * query.pageSize}`) }
        `

        return { list, total }
    }

    findOne(id: number) {
        return this.prisma.article.findUnique({
            where: { id }
        })
    }

    update(id: number, updateArticleDto: UpdateArticleDto) {
        return this.prisma.article.update({
            where: { id },
            data: updateArticleDto
        })
    }

    remove(id: number) {
        return this.prisma.article.delete({
            where: { id }
        })
    }
}
